import 'package:dart_serve_study/dart_serve_study.dart';
import '../model/read.dart';

class ReadsController extends ResourceController {
  ManagedContext context;

  // ignore: sort_constructors_first
  ReadsController(this.context);

  //获取
  @Operation.get()
  Future<Response> getAllReads() async {
    final readQuery = Query<Read>(context);
    return Response.ok(await readQuery.fetch());
  }

  

  @Operation.get('id')
  Future<Response> getRead(@Bind.path('id') int id) async {
    final readQuery = Query<Read>(context)
      ..where((read) => read.id).equalTo(id);

    final read = await readQuery.fetchOne();

    if (read == null) {
      return Response.notFound(body: 'Item not found.');
    }
    return Response.ok(read);
  }

  //增加
  @Operation.post()
  Future<Response> createNewRead(@Bind.body() Read body) async {
    final readQuery = Query<Read>(context)..values = body;
    final insertedRead = await readQuery.insert();
    return Response.ok(insertedRead);
  }

  //修改
  @Operation.put('id')
  Future<Response> updatedRead(
      @Bind.path('id') int id, @Bind.body() Read body) async {
    final readQuey = Query<Read>(context)
      ..values = body
      ..where((read) => read.id).equalTo(id);
    //as  翻译说是保存的意思
    final updatedQuery = await readQuey.updateOne();
    if (updatedQuery == null) {
      return Response.notFound(body: 'Item not found.');
    }
    return Response.ok(updatedQuery);
  }

  //删除
  @Operation.delete('id')
  Future<Response> deletedRead(@Bind.path('id') int id) async {
    final readQuey = Query<Read>(context)..where((x) => x.id).equalTo(id);
    final int deleteCount = await readQuey.delete();

    if (deleteCount == 0) {
      return Response.notFound(body: 'Item not found.');
    }
    return Response.ok('Deleted $deleteCount items.');
  }
}
